<script lang="ts" setup>
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import { isEmpty } from 'lodash-es'
import * as echarts from 'echarts'

const props = defineProps({
	chartData: {
		type: Object,
		default: () => ({}),
	},
})

const echartRef = ref(null)
const isHidden = ref(true)
let myChart: any = null

function setChsrts() {
	// 假设数据量为 dataLength
	const dataLength = 5
	const baseHeight = 200 // 基础高度
	const baseWidth = 400 // 基础宽度
	const heightPerItem = 20 // 每个数据项额外增加的高度
	const widthPerItem = 30 // 每个数据项额外增加的宽度

	const containerHeight = baseHeight + dataLength * heightPerItem
	const containerWidth = baseWidth + dataLength * widthPerItem
	const echartEle: any = echartRef.value
	// 动态调整容器大小
	if (echartEle) {
		echartEle.style.height = `${containerHeight}px`
		echartEle.style.width = `${containerWidth}px`
	} else {
		console.error('ECharts 容器未正确引用')
		return
	}

	try {
		// 检查是否已经初始化过图表
		if (myChart) {
			myChart.dispose() // 销毁旧的图表实例
		}

		// 初始化图表
		myChart = echarts.init(echartEle)

		// 检查图表数据是否有效
		if (!props.chartData?.data) {
			console.error('图表数据未正确设置')
			return
		}

		// 设置图表配置
		myChart.setOption(props.chartData.data)

		// 调整图表大小以适应容器
		myChart.resize({
			width: containerWidth,
			height: containerHeight,
		})
	} catch (error) {
		console.error('初始化图表时发生错误:', error)
	}
}

function handleResize() {
	if (myChart) {
		myChart.resize() // 调用resize方法重新渲染图表
	}
}

function removeResizeListener() {
	if (myChart) {
		myChart.dispose() // 销毁图表实例
	}
	window.removeEventListener('resize', handleResize)
}

onMounted(async () => {
	if (props.chartData && !isEmpty(props.chartData)) {
		isHidden.value = false
		await nextTick()
		setChsrts()
		window.addEventListener('resize', handleResize)
	}
})

onBeforeUnmount(() => {
	removeResizeListener()
})
</script>
<template>
	<div v-if="!isHidden" :id="chartData.id" ref="echartRef" class="res-chart"></div>
</template>
<style scoped lang="scss">
.res-chart {
	background-color: #fff;
	border-radius: 8px;
	// width: max-content;
	width: 1200px;
	max-width: 100%;
	height: 35vh;
	min-height: 240px;
	max-height: 540px;
	// padding: 6px;
}
</style>
